<template>
  <div class="data">
    <div style="
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        margin-bottom: 15px;
      ">
      <div style="
          display: flex;
          justify-content: flex-start;
          align-items: center;
          flex-wrap: wrap;
        ">
        <el-radio-group v-model="data_type" @change="changeDateType">
          <el-radio-button label="今日" />
          <el-radio-button label="昨日" />
          <el-radio-button label="近7日" />
          <el-radio-button label="近15日" />
          <el-radio-button label="近30日" />
        </el-radio-group>
        <div style="margin-left: 15px; display: flex; align-items: center; margin-left: 15px;">
          <el-date-picker format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="changeDate" v-model="date_range"
            type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
            style="width: 150px;" />
          <el-button :icon="Refresh" @click="getRow()" circle />

        </div>

      </div>
    </div>

    <div style="width: 50%;">
      <el-segmented v-model="radio_value" :options="radio" @change="radioChange" block />
      <!-- <el-radio-group v-model="radio" @change="radioChange">
      <el-radio-button label="新增用户" value="新增用户" />
      <el-radio-button label="所有用户" value="所有用户" /> -->
      <!-- </el-radio-group> -->
    </div>
    <avue-crud ref="gameListRef" v-model="form" :option="option" @refresh-change="getList" @row-save="rowSave"
      @row-update="rowUpdate" :data="data" :page="page" @size-change="sizeChange" @current-change="currentChange"
      @search-change="searchChange" @search-reset="searchReset">
      <template #menu="{ row, index, size }">
        <el-button type="primary" text @click="look(row)">查看</el-button>
      </template>
    </avue-crud>
  </div>
  <el-dialog v-model="dialogVisible" width="100%" :before-close="handleClose" @opened="resizeChart">
    <div :class="{ 'rotate-height': isMobile }">
      <div id="main" ref="chartContainer" :style="chartStyle" :class="{ 'rotate-90': isMobile }"></div>
    </div>
  </el-dialog>
</template>
<!--  :upload-preview="uploadPreview" -->
<!-- :upload-before="fileTest" :upload-after="uploadAfter" -->
<!-- :upload-before="fileTest" -->
<script setup>
import { Refresh } from "@element-plus/icons-vue";
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from "vue";
import gameList_me from "@/options/gameList_me";
import * as echarts from 'echarts';
import { ElMessageBox, ElMessage, ElLoading } from "element-plus";
import { getGameListLog, delGame, addGame, editGame, getGameStockRecords } from "@/apis/admin";
const option = gameList_me;
const radio = ref(['新增用户', '全部用户'])
const radio_value = ref('新增用户')
const data = ref([]);
const form = ref({});
const data_type = ref("今日");
const date_range = ref("");
const page = reactive({
  total: 0,
  searchInfo: {},
  currentPage: 1,
  pageSize: 10,
  startime: Math.ceil(Date.now() / 1000),
  endtime: Math.ceil(Date.now() / 1000)
});

const isNew = ref(1)
const dialogVisible = ref(false);

// 切换新增/所有用户
const radioChange = (val) => {
  if (val == '新增用户') {
    isNew.value = 1;
  } else {
    isNew.value = 0;
  }
  console.log(val)
  getList()
}

const tableLoading = ref(false);
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
// const isMobile = false;
const chartStyle = computed(() => {
  return {
    width: isMobile ? '100%' : '100%',
    height: isMobile ? '300px' : '300px',
  };
});

const sizeChange = (val) => {
  page.pageSize = val;
  getList();
};
const currentChange = (val) => {
  page.currentPage = val;
  getList();
};
const searchChange = (form, done) => {
  page.searchInfo = form;
  page.currentPage = 1;
  getList();
  done();
};
const searchReset = () => {
  page.searchInfo = {};
  page.currentPage = 1;
  getList();
};
const rowSave = async (row, done, loading) => {
  const res = await addGame.post("", { ...row, isRecommend: 0 });
  if (res.code == 200) {
    done();
    ElMessage.success("添加成功!");
    getList();
  } else {
    ElMessage.error("添加失败!");
  }
};

const look = async (row) => {
  dialogVisible.value = true;
  console.log(row)
  nextTick(() => {
    initChart(row.gameCode);
  });
}
// 单项更新
const rowUpdate = async (row, index, done, loading) => {
  const res = await editGame.post("", row);
  if (res.code == 200) {
    done();
    ElMessage.success("编辑成功!");
    getList();
  } else {
    ElMessage.error("编辑失败!");
  }
};

// 获取列表
const getList = () => {
  tableLoading.value = true;
  getGameListLog
    .post("", {
      isNew: isNew.value,
      // searchInfo: page.searchInfo,
      page: page.currentPage,
      pageSize: page.pageSize,
      startTime: page.startime,
      endTime: page.endtime
    })
    .then((res) => {
      if (res.code == 200) {
        console.log('aaa', res)
        page.total = res.data.total;
        data.value = res.data.list || [];
        let all = 0
        for (let i = 0; i < res.data.list.length; i++) {
          const element = res.data.list[i];
          all += element.bettingTotal
        }
        for (let i = 0; i < res.data.list.length; i++) {
          const element = res.data.list[i];
          element.all = (element.bettingTotal / all) * 100;
        }
      }
      tableLoading.value = false;
      window.loading(0)
    });
};

let myChart = null;
const chartContainer = ref(null);

const initChart = (name) => {
  getGameStockRecords
    .post('', {
      gameCode: name
    })
    .then((res) => {
      let list = res.data.lists;
      if (chartContainer.value) {
        myChart = echarts.init(chartContainer.value, 'dark');
        // Prepare series data
        let totalLength = list[0].stocks.length;
        if (totalLength < 240) {
          const missingLength = 240 - totalLength;
          for (let i = 0; i < list.length; i++) {
            for (let j = 0; j < missingLength; j++) {
              list[i].stocks.unshift({
                stocks: 0,
                time: 0
              });
            }
          }
          totalLength = 240;
        }
        const seriesData = list.map((item, index) => ({
          smooth: true,
          name: item.gameCode.includes(':') ? item.gameCode.replace(':0', ':小').replace(':1', ':中').replace(':2', ':大') : item.gameCode,
          type: 'line',
          data: item.stocks.map(value => value.stocks / 100) // Divide each value by 100
        }));
        // Calculate the interval for xAxis labels

        const interval = Math.ceil(totalLength / 24); // 24 hours in a day
        // 绘制图表
        myChart.setOption({
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: list.map(item => item.gameCode.includes(':') ? item.gameCode.replace(':0', ':小').replace(':1', ':中').replace(':2', ':大') : item.gameCode),
            selected: list.reduce((acc, item) => {
              acc[item.gameCode] = false;
              return acc;
            }, {}),
            top: isMobile ? 0 : 0
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
            top: 0
          },
          toolbox: isMobile ? {} : {
            feature: {
              saveAsImage: {},
              dataZoom: {},
              dataView: {},
              restore: {},
              magicType: {
                type: ['line', 'bar']
              },
              myFullScreen: {
                show: true,
                title: '全屏',
                icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891',
                onclick: () => {
                  const element = chartContainer.value;
                  if (element) {
                    if (document.fullscreenElement) {
                      document.exitFullscreen();
                    } else {
                      if (element.requestFullscreen) {
                        element.requestFullscreen();
                      } else if (element.webkitRequestFullscreen) { // Safari
                        element.webkitRequestFullscreen();
                      } else if (element.msRequestFullscreen) { // IE11
                        element.msRequestFullscreen();
                      } else if (element.mozRequestFullScreen) { // Firefox
                        element.mozRequestFullScreen();
                      } else if (element.webkitEnterFullscreen) { // iOS Safari
                        element.webkitEnterFullscreen();
                      }
                    }
                  }
                  // 强制触发resize事件，确保图表在全屏后正确渲染
                  setTimeout(() => {
                    window.dispatchEvent(new Event('resize'));
                  }, 100);
                }
              }
            },
            right: 0,
            top: 20,
            orient: 'horizontal'
          },
          dataZoom: [
            {
              type: 'slider',
              show: true,
              xAxisIndex: [0],
              start: 0,
              end: 100
            },
            {
              type: 'inside',
              xAxisIndex: [0],
              start: 0,
              end: 100
            }
          ],
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: list[0].stocks.map(stock => {
              const date = new Date(stock.time * 1000); // Convert timestamp to milliseconds
              date.setUTCHours(date.getUTCHours() + 8); // Convert to Beijing Time
              const hours = date.getUTCHours().toString().padStart(2, '0');
              const minutes = date.getUTCMinutes().toString().padStart(2, '0');
              return `${hours}:${minutes}`;
            })
          },
          yAxis: {
            type: 'value',
            min: (value) => value.min - value.max * 0.25,
            max: (value) => value.max * 1.25
          },
          series: seriesData
        });

        // Add click event listener to legend
        myChart.on('legendselectchanged', function (params) {
          const selectedSeriesNames = Object.keys(params.selected).filter(name => params.selected[name]);
          if (selectedSeriesNames.length > 0) {
            const selectedData = selectedSeriesNames.flatMap(name => {
              const series = seriesData.find(series => series.name === name);
              return series ? series.data : [];
            });
            let minValue = Math.min(...selectedData);
            let maxValue = Math.max(...selectedData);
            if (minValue === maxValue) {
              minValue -= 1;
              maxValue += 1;
            }
            myChart.setOption({
              yAxis: {
                min: minValue - maxValue * 0.25,
                max: maxValue * 1.25
              }
            });
            // Force refresh the chart to ensure it updates immediately
            setTimeout(() => {
              myChart.resize();
            }, 100);
          }
        });
      }
    })
};

const resizeChart = () => {
  if (myChart) {
    myChart.resize();
  }
};

const handleCollapseChange = (activeNames) => {
  if (activeNames.length > 0) {
    nextTick(() => {
      resizeChart();
    });
  }
};

onMounted(() => {
  getList();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  if (myChart) {
    myChart.dispose();
  }
});

const changeDate = () => {
  if (date_range.value === "" || date_range.value == null) {
    data_type.value = "今日";
  } else {
    data_type.value = "";
  }
  getRow();
};
const convertToTimestamp = (dateString) => {
  return Date.parse(new Date(dateString));
};

const getRow = () => {
  let start = "";
  let end = "";
  if (date_range.value != "" && date_range.value != null) {
    start = convertToTimestamp(date_range.value[0]);
    end = convertToTimestamp(date_range.value[1]);
  } else {
    const now = new Date();
    if (data_type.value == "今日") {
      start = Date.now();
      end = start || Date.now();
    } else if (data_type.value == "昨日") {
      const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
      yesterday.setHours(8, 0, 0, 0);

      const todayMorning = new Date(now);
      todayMorning.setHours(8, 0, 0, 0);

      start = Date.parse(yesterday);
      end = Date.parse(todayMorning) - 1 - 1000;
    } else if (data_type.value == "近7日") {
      const lastWeek = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      lastWeek.setHours(8, 0, 0, 0);

      const todayMorning = new Date(now);
      todayMorning.setHours(8, 0, 0, 0);

      start = Date.parse(lastWeek);
      end = Date.parse(todayMorning) - 1;
    } else if (data_type.value == "近15日") {
      const lastTwoWeeks = new Date(now.getTime() - 15 * 24 * 60 * 60 * 1000);
      lastTwoWeeks.setHours(8, 0, 0, 0);

      const todayMorning = new Date(now);
      todayMorning.setHours(8, 0, 0, 0);

      start = Date.parse(lastTwoWeeks);
      end = Date.parse(todayMorning) - 1;
    } else if (data_type.value == "近30日") {
      const lastMonth = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
      lastMonth.setHours(8, 0, 0, 0);

      const todayMorning = new Date(now);
      todayMorning.setHours(8, 0, 0, 0);

      start = Date.parse(lastMonth);
      end = Date.parse(todayMorning) - 1;
    }
  }
  let convertTimestamp = (timestamp) => {
    const date = new Date(timestamp * 1000); // 将时间戳转换为毫秒
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2); // 补全两位数
    const day = ('0' + date.getDate()).slice(-2);
    const hours = ('0' + date.getHours()).slice(-2);
    const minutes = ('0' + date.getMinutes()).slice(-2);
    const seconds = ('0' + date.getSeconds()).slice(-2);

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  page.startime = Math.ceil(start / 1000);
  page.endtime = Math.ceil(end / 1000);
  console.log('startTime:', convertTimestamp(Math.ceil(start / 1000)))
  console.log('endsTime:', convertTimestamp(Math.ceil(end / 1000)))
  getList()
};


const changeDateType = () => {
  if (data_type.value !== "") date_range.value = "";
  getRow();
};

const handleClose = (done) => {
  dialogVisible.value = false;
  done();
};
</script>
<style lang="scss" scoped>
.statistic-card {
  text-align: center;
  margin-bottom: 10px;
  //padding: 20px;
  border-radius: 4px;
  background-color: #f5f5f5;
}

.data {
  width: 100%;

  .charts-box {
    margin-top: 15px;
    width: 100%;
    height: 500px;
    background: #f5f5f5;
    border-radius: 8px;
    box-sizing: border-box;
    padding: 10px 15px;
  }
}

.main-content {
  padding: 0 !important;
}

.fullscreen {
  /* position: fixed !important;
  top: -45% !important;
  left: 0 !important; */
  width: 100vh !important;
  height: 100vw !important;
  z-index: 9999 !important;
}

.rotate-90 {
  /* transform: rotate(90deg);
  transform-origin: bottom left;
  top: -300px; */
}

.rotate-height {
  /* height: 600px; */
}

/* 确保el-collapse-item内容完全展示 */
.el-collapse-item__content {
  overflow: visible !important;
}
</style>